package com.ruoyi.web.controller.tech;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.Technicians;
import com.ruoyi.system.service.ITechniciansService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

@Anonymous  //此注解是不加权限直接可以调用该类的所有接口
@RestController
@CrossOrigin(origins = "*")  //这里是解决前端跨域的问题
@RequestMapping("/html")
public class HtmlTechniciansController extends BaseController {

    @Autowired
    private ITechniciansService techniciansService;

    // 最佳实践 (结合两版优点)
    @PostMapping("/upload")
    public AjaxResult uploadTechnician(
            @RequestParam String name,
            @RequestParam String phone,
            @RequestParam(required = false) String message,
            @RequestParam MultipartFile mainImg,
            @RequestParam MultipartFile listImg) {

        try {
            // 1. 获取配置的上传根目录
            String baseDir = RuoYiConfig.getProfile(); // 自动适配Windows/Linux

            // 2. 生成日期目录（yyyy/MM/dd）
            String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());

            // 3. 构建完整存储路径
            String savePath = Paths.get("technician", dateDir).toString();
            String absolutePath = Paths.get(baseDir, savePath).toString();

            // 4. 确保目录存在
            Files.createDirectories(Paths.get(absolutePath));

            // 5. 生成唯一文件名（保留扩展名）
            String mainImgName = generateFileName(mainImg.getOriginalFilename());
            String listImgName = generateFileName(listImg.getOriginalFilename());

            // 6. 保存文件
            Path mainImgPath = Paths.get(absolutePath, mainImgName);
            Path listImgPath = Paths.get(absolutePath, listImgName);
            mainImg.transferTo(mainImgPath);
            listImg.transferTo(listImgPath);

            // 7. 构建标准化数据库路径
            String dbMainPath = "/technician/" + dateDir + "/" + mainImgName;
            String dbListPath = "/technician/" + dateDir + "/" + listImgName;

            // 8. 保存到数据库
            Technicians tech = new Technicians();
            tech.setName(name);
            tech.setPhone(phone);
            tech.setMessage(message);
            tech.setMainImg(dbMainPath); // 示例：/technician/2025/04/09/abc123.jpg
            tech.setListImg(dbListPath);
            techniciansService.insertTechnicians(tech);

            return AjaxResult.success("上传成功");
        } catch (Exception e) {
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }

    // 生成唯一文件名（UUID + 扩展名）
    private String generateFileName(String originalName) {
        String ext = "";
        if (originalName != null && originalName.contains(".")) {
            ext = originalName.substring(originalName.lastIndexOf("."));
        }
        return UUID.randomUUID().toString() + ext;
    }

    //列表
    //http://127.0.0.1:9070/html/list
    @PostMapping("/list")
    public AjaxResult list(@Validated @RequestBody Technicians technicians) {
        technicians.setStatus("1"); //只显示上架的
        List<Technicians> list = techniciansService.selectList(technicians);
        return success(list);
    }

    //http://127.0.0.1:9070/html/30
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(techniciansService.selectById(id));
    }

    //分页显示 http://127.0.0.1:9070/html/list?pageNum=1&pageSize=12&type=5
    @GetMapping("/list")
    public TableDataInfo list(
            @RequestParam(required = false) Long type,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "12") Integer pageSize) {

        // 1. 参数校验
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1 || pageSize > 100) {
            pageSize = 12; // 限制每页最大100条
        }

        // 2. 构建查询条件
        Technicians query = new Technicians();
        if (type != null) {
            query.setType(type);
        }

        // 3. 启动分页（使用PageHelper）
        PageHelper.startPage(pageNum, pageSize, "create_time DESC"); // 默认按创建时间倒序

        // 4. 查询数据
        List<Technicians> list = techniciansService.selectPageList(query);

        // 5. 处理图片路径
        list.forEach(tech -> {
            tech.setMainImg(formatImagePath(tech.getMainImg()));
            tech.setListImg(formatImagePath(tech.getListImg()));
        });

        // 6. 返回分页结果
        return buildDataTable(list);
    }

    /**
     * 格式化图片路径
     */
    private String formatImagePath(String imgPath) {
        if (StringUtils.isBlank(imgPath)) {
            return "/static/img/default-tech.jpg";
        }

        // 统一路径分隔符
        String normalizedPath = imgPath.replace("\\", "/");

        // 已经是完整路径则直接返回
        if (normalizedPath.startsWith("http") || normalizedPath.startsWith("/profile")) {
            return normalizedPath;
        }

        // 添加profile前缀（确保以/开头）
        return RuoYiConfig.getProfilePrefix() +
                (normalizedPath.startsWith("/") ? normalizedPath : "/" + normalizedPath);
    }

    /**
     * 构建分页响应
     */
    private TableDataInfo buildDataTable(List<?> list) {
        TableDataInfo response = new TableDataInfo();
        response.setCode(HttpStatus.SUCCESS);
        response.setMsg("查询成功");
        response.setRows(list);
        response.setTotal(new PageInfo<>(list).getTotal());
        return response;
    }

}
